package com.netty.httpserver;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

@SuppressWarnings("deprecation")
public class HttpServletResponse {
	private ChannelHandlerContext ctx;

	private HttpRequest req;

	public HttpServletResponse(ChannelHandlerContext ctx, HttpRequest msg) {
		this.ctx = ctx;
		this.req = msg;
	}

	public void write(String out) {
		FullHttpResponse response = null;
		try {
			response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
					Unpooled.wrappedBuffer(out.getBytes(CharsetUtil.UTF_8)));

			String contentType = req.headers().get("Accept").split(",")[0];
			response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType+"; charset=UTF-8");
			response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
			response.headers().set(HttpHeaderNames.EXPIRES, 0);
			if (HttpHeaders.isKeepAlive(req)) {
				response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.CONNECTION);
			}
			ctx.write(response);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ctx.flush();
		}

	}

}
